import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'indexPage.dart';
import 'utils/platformUtils.dart';
import 'utils/httpUtils.dart';
class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _LoginPageHome();
}

class _LoginPageHome extends State<LoginPage> {
  //焦点
  FocusNode _focusNodeUserName = FocusNode();
  FocusNode _focusNodePassword = FocusNode();

  //用户名输入框控制器
  TextEditingController _userNameController = TextEditingController();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey();
  var _password = '';
  var _userName = '';
  var _isShowPw = false;
  var _isShowClear = false;

  @override
  void initState() {
    // TODO: implement initState
    _focusNodeUserName.addListener(_focusNodeListener);
    _focusNodePassword.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userNameController.addListener(() {
      var value = _userNameController.text;
      if (value.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _focusNodeUserName.removeListener(_focusNodeListener);
    _focusNodePassword.removeListener(_focusNodeListener);
    _userNameController.dispose();
    super.dispose();
  }

  Future _focusNodeListener() async {
    if (_focusNodeUserName.hasFocus) {
      print('用户名框获取焦点');
      _focusNodePassword.unfocus();
    }
    if (_focusNodePassword.hasFocus) {
      print('密码框获取焦点');
      _focusNodeUserName.unfocus();
    }
  }

  /// 验证手机号
  String validateUserName(String value) {
    RegExp exp = RegExp(r'^(1[345789][0-9])\d{8}$');
    if (value.isEmpty) {
      return '用户名不能为空';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确手机号';
    }
    return null;
  }

  ///验证密码
  String validatePassword(String value) {
    if (value.isEmpty) {
      return '密码不能为空';
    } else if (value.trim().length < 6) {
      return '密码长度不正确';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
    Widget logoImageArea = Container(
      alignment: Alignment.topCenter,
      child: ClipOval(
        child: Image.asset(
          "images/logo.png",
          height: 100,
          width: 100,
          fit: BoxFit.cover,
        ),
      ),
    );
    //输入文本框
    Widget inputTextArae = new Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Colors.white),
      child: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextFormField(
              controller: _userNameController,
              focusNode: _focusNodeUserName,
              //设置键盘类型
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                labelText: '用户名',
                hintText: '请输入手机号',
                prefixIcon: Icon(Icons.person),
                //尾部添加清楚按钮
                suffixIcon: (_isShowClear)
                    ? IconButton(
                        icon: Icon(Icons.clear),
                        onPressed: () {
                          _userNameController.clear();
                        },
                      )
                    : null,
              ),
              //验证用户名
              validator: validateUserName,
              //保存数据
              onSaved: (String value) {
                _userName = value;
              },
            ),
            TextFormField(
              focusNode: _focusNodePassword,
              decoration: InputDecoration(
                labelText: '密码',
                hintText: '请输入密码',
                prefixIcon: Icon(Icons.lock),
                suffixIcon: IconButton(
                  icon: Icon(
                      (_isShowPw) ? Icons.visibility : Icons.visibility_off),
                  onPressed: () {
                    setState(() {
                      _isShowPw = !_isShowPw;
                    });
                  },
                ),
              ),
              obscureText: !_isShowPw,
              validator: validatePassword,
              onSaved: (String value) {
                _password = value;
              },
            )
          ],
        ),
      ),
    );
    //登录按钮区域
    Widget loginButtonArea = Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      child: RaisedButton(
          color: Colors.blue[300],
          child: Text(
            "登录",
            style: Theme.of(context).primaryTextTheme.headline3,
          ),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          onPressed: () {
            _focusNodePassword.unfocus();
            _focusNodeUserName.unfocus();
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              print("$_userName + $_password");
              HttpUtils.get("https://httpbin.org/ip");
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(builder: (context) {
              //     return IndexPage(title: 'index');
              //   }),
              // );
            }
          }),
    );
    Widget listView = ListView(
      children: [
        SizedBox(
          height: ScreenUtil().setHeight(80),
        ),
        logoImageArea,
        SizedBox(
          height: ScreenUtil().setHeight(80),
        ),
        inputTextArae,
        SizedBox(
          height: ScreenUtil().setHeight(80),
        ),
        loginButtonArea
      ],
    );
    var widthAll = MediaQuery.of(context).size.width;
    return Scaffold(
        backgroundColor: Colors.white,
        //外层添加一个手势，用于点击空白部分回收键盘
        body: PlatformUtils.isWeb
            ? (Container(
                margin:
                    EdgeInsets.only(left: widthAll / 4, right: widthAll / 4),
                child: listView,
              ))
            : (GestureDetector(
                onTap: () {
                  print('点击了空白区域');
                  _focusNodeUserName.unfocus();
                  _focusNodePassword.unfocus();
                },
                child: listView)));
  }
}
